import {reqCartList,reqDeleteCartById,reqUpdateCheckedById} from '@/api'

const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList
    }
}
const actions = {
    // 获取购物车列表数据
    async getCartList({commit}){
        let result =  await reqCartList()
        if(result.code == 200){
            commit('GETCARTLIST',result.data)
        }
    },
    // 删除购物车中某个商品
    async deleteCartListBySkuId({commit},skuId){
        let result = await reqDeleteCartById(skuId)
        if(result.code = 200){
            return 'ok'
            // commit('DELETECARTBYSKUID',result.data)
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除购物车中全部勾选的商品
    deleteAllCheckedCart({dispatch,getters}){
        // context：小仓库
        // 获取购物车全部的商品(数组)
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item=>{
            // 删除isChecked为1(被选中)的
            let promise = item.isChecked==1?dispatch('deleteCartListBySkuId',item.skuId):''
            // 将每一次返回的promise添加到数组中
            PromiseAll.push(promise)
        })
        // 只有全部的p1|p2都成功，返回结果才成功
        // 有一个失败，返回结果为失败
        return Promise.all(PromiseAll)
    },

    // 修改购物车某个产品选中状态
    async updateCheckedById({commit},{skuId,isChecked}){
        let result = await reqUpdateCheckedById(skuId,isChecked)
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },

    //全选
    updateAllCartIsChecked({dispatch,state},isChecked){
        let promiseAll = []
        state.cartList[0].cartInfoList.forEach((item)=>{
            let promise =  dispatch('updateCheckedById',{
                skuId:item.skuId,
                isChecked
            })
            promiseAll.push(promise)
        })
        // 最终返回的结果
        return Promise.all(promiseAll)
    } 

}
const getters = {
    cartList(state){
        return state.cartList[0] || {}
    },

}

export default{
    state,
    mutations,
    actions,
    getters
}